package com.farm.kaiping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.farm.kaiping.entity.Building;
import com.farm.kaiping.entity.Pig;
import com.farm.kaiping.entity.Pigpen;
import com.farm.kaiping.po.BuildingPO;
import com.farm.kaiping.po.PigPO;
import com.farm.kaiping.po.PigpenPO;
import com.farm.kaiping.service.BuildingLogicService;
import com.farm.kaiping.service.BuildingService;
import com.farm.kaiping.service.PigService;
import com.farm.kaiping.service.PigpenService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
@AllArgsConstructor
public class BuildingLogicServiceImpl implements BuildingLogicService {

    private final BuildingService buildingService;
    private final PigpenService pigpenService;
    private final PigService pigService;

    /**
     * 删除前校验
     * @param buildingPO
     */
    @Override
    public void checkBeforeRemove(BuildingPO buildingPO) {
        if (ObjectUtil.isEmpty(buildingPO.getBatchDel())) {
            throw new RuntimeException("删除数据未选择");
        }
        // 栏舍校验
        PigpenPO pigpenPO = new PigpenPO();
        pigpenPO.setBuildingIdList(buildingPO.getBatchDel());
        List<Pigpen> pigpenList = pigpenService.getPigpenList(pigpenPO);
        if (ObjectUtil.isNotEmpty(pigpenList)){
            throw new RuntimeException("该厂房下存在圈栏舍,请先清除栏舍");
        }
        // 猪只校验
        PigPO pigPO = new PigPO();
        pigPO.setBuildingIdList(buildingPO.getBatchDel());
        List<Pig> pigList = pigService.getPigList(pigPO);
        if (ObjectUtil.isNotEmpty(pigList)) {
            throw new RuntimeException("该厂房下存在猪只,请先清除猪只");
        }

    }

    /**
     * 获取一条数据
     *
     * @param buildingPO
     * @return
     */
    @Override
    public BuildingPO getBuilding(BuildingPO buildingPO) {
        Building building = buildingService.getBuilding(buildingPO);
        BuildingPO result = BeanUtil.copyProperties(building, BuildingPO.class);
        PigpenPO pigpenPO = new PigpenPO();
        pigpenPO.setBuildingId(building.getId());
        List<Pigpen> pigpenList = pigpenService.getPigpenList(pigpenPO);
        result.setPigpenCount(pigpenList.size());

        List<Pig> pigList = pigService.list(new LambdaQueryWrapper<Pig>().eq(Pig::getDelFlag,0)
                .eq(Pig::getBuildingId,building.getId()).in(Pig::getHealthStatus,0,1).in(Pig::getSalesStatus,-1,0,1));
        result.setPigCount(pigList.size());
        return result;
    }
}
